<template>
  <div class="search">
    <input type="text" class="city-search" placeholder="请输入城市名称" v-model="keyword">
    <div class="search-conent" ref="search" v-show="keyword">
      <ul>
        <li v-for="item in list" :key="item.id" class="search-item" @click='handleCityClick(item.name)'>{{item.name}}</li>
        
        <li class="search-item" v-show='hasNoData'>没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from "better-scroll";
export default {
  name: "citySearch",
  props: {
    cities: Object
  },
  data() {
    return {
      keyword: "",
      list: [],
      timer: null,

    };
  },
  methods: {
    handleCityClick(city){
      // vuex提供了一个dispatch方法,方法定义在store.js中的actions中
      this.$store.commit('changeCity',city)
      // alert(city)
      // 点击地名后实现路由跳转至首页
      this.$router.push('/')
    }
  },
  mounted() {
    this.scroll = new Bscroll(this.$refs.search);
  },
  computed: {
    hasNoData(){
      return !this.list.length
    }
  },
  watch: {
    keyword() {
      if (!this.timer) {
        clearTimeout(this.timer);
      }
      if (!this.keyword) {
        this.list = [];
        return;
      }
      this.timer = setTimeout(() => {
        const result = [];
        // 遍历cities这个对象，对其中的每一项值进行遍历，获取到与输入内容有相同数据的对象存储在result这个空数组中，再把数组赋值给list。再对list进行v-for循环遍历
        for (let i in this.cities) {
          this.cities[i].forEach(val => {
            if (
              val.spell.indexOf(this.keyword) > -1 ||
              val.name.indexOf(this.keyword) > -1
            ) {
              result.push(val);
            }
          });
        }
        this.list = result;
      }, 100);
    }
  }
};
</script>

<style lang="less" scoped>
@import "~@/assets/styles/common.less";
.search {
  height: 0.72rem;
  padding: 0.1rem;
  background-color: @baseColor;
  .city-search {
    width: 100%;
    height: 0.72rem;
    line-height: 0.72rem;
    box-sizing: border-box;
    padding: 0.1rem;
    text-align: center;
    border-radius: 0.1rem;
    color: #333;
  }
  .search-conent {
    position: absolute;
    z-index: 1;
    top: 1.76rem;
    left: 0;
    bottom: 0;
    right: 0;
    overflow: hidden;
    background: #fff;
    .search-item {
      line-height: 0.62rem;
      padding-left: 0.2rem;
      color: #666;

      border-bottom: 1px solid #ccc;
    }
  }
}
</style>
